<template>
  <div class="index-container">
      <RelateTarget ref="targetInfo" :isMark="true" :preivew="true" :isSHow="false" :target="targetId"/>
      <!-- <table class="index-table" id="table" border="1">
        <thead>
          <tr>
            <th :colspan="level">指标</th>
            <th style="width: 11vh;text-align: center">痕迹<br>(支撑材料)</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="!flattenIndexList.length">
            <td class="empty" colspan="2">没有数据</td>
          </tr>
          <template v-if="level === 1">
            <tr v-for="(item,index) in flattenIndexList" :key="index">
              <!-- <td v-if="item.p">{{ item.p.content }}</td> 
              <td v-if="item.c">
                {{ item.c.index }}、{{ item.c.content }}
                <span class="desc" v-if="item.c.evaluation"> 考核标准：{{ item.c.evaluation }} </span>
                <span class="fs"> ({{ item.c.score }}分) </span>
              </td>
              <td> 
                  <div class="markBtn" @click="handleOpenInfo(item.c.id)">
                    <span class=" ml">{{ item.c.id }}</span>痕迹
                  </div>
                </td>
            </tr>
          </template>
          <template v-if="level === 2">
            <tr v-for="(item,index) in flattenIndexList" :key="index">
              <td v-if="item.p">
                  {{ item.p.index }}、{{ item.p.content }}
                  <span class="desc" v-if="item.p.evaluation"> 考核标准：{{ item.p.evaluation }} </span>
                  <span class="fs"> ({{ item.p.score }}分) </span>
              </td>
              <td v-if="item.c" :colspan="item.p ? '':2">
                  {{ item.c.index }}、{{ item.c.content }}
                  <span class="desc" v-if="item.c.evaluation"> 考核标准：{{ item.c.evaluation }} </span>
                  <span class="fs"> ({{ item.c.score }}分) </span>
              </td>
              <td> 
                  <div class="markBtn" @click="handleOpenInfo(item.c.id)">
                    <span class=" ml">{{ item.c.id }}</span>痕迹
                  </div>
                  <el-button type="text" icon="el-icon-plus" @click="handleOpenUpload(item.c.id)">添加痕迹</el-button>
                </td>
            </tr>
          </template>
          <template v-if="level === 3">
            <tr v-for="(item,index) in flattenIndexList" :key="index">
              <td v-if="item.p" style="width:46%">
                  {{ item.p.index }}、{{ item.p.content }}
                  <span class="desc" v-if="item.p.evaluation"> 考核标准：{{ item.p.evaluation }} </span>
                  <span class="fs"> ({{ item.p.score }}分) </span>
              </td>
              <td v-if="item.s">
                  {{ item.s.index }}、{{ item.s.content }}
                  <span class="desc" v-if="item.s.evaluation"> 考核标准：{{ item.s.evaluation }} </span>
                  <span class="fs"> ({{ item.s.score }}分) </span>
              </td>
              <td v-if="item.c" :colspan="!item.s && !item.p ? 3: item.s ? '': 2">
                  {{ item.c.index }}、{{ item.c.content }}
                  <span class="desc" v-if="item.c.evaluation"> 考核标准：{{ item.c.evaluation }} </span>
                  <span class="fs"> ({{ item.c.score }}分) </span>
              </td>
              <!-- <td> {{ item.c.id }}</td> -
              <td> 
                <div class="markBtn" @click="handleOpenInfo(item.c.id)">
                  <span class=" ml">{{ item.c.id }}</span>痕迹
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table> -->

    <!-- <div class="index-items">
      <div class="content" v-for="(item,index) in indexList" :key="index">
        <div class="content-header">
          {{ index+1 }}、<span class="content-header_title">{{item.content}}</span>
          <span class="content-header_score">{{ item.score || 0 }}分</span>
          <div class="content-header_btngroup">
            <el-button type="text" icon="el-icon-plus" @click="handleOpenUpload(item.id)">添加痕迹</el-button>
            <el-button type="text" icon="el-icon-search" @click="handleOpenInfo(item.id)">查阅痕迹</el-button>
            <!-- <el-button type="text" @click="handleOpenInfo(item.id)"> 
                    <span style="color:red;">{{ item.score }}</span> 条痕迹
                  </el-button> 
          </div>
        </div>
        <div class="content-time"><span v-show="item.create_time">创建时间：</span> {{ item.create_time | formatTime}}</div>
        <div class="content-desc"><span v-show="item.evaluation">考核标准: </span> {{ item.evaluation }}
        </div>
        <template>
          <div class="sub-wrapper">
            <div class="content" v-for="(subItem,subIndex) in item.child" :key="subIndex">
              <div class="content-header">
                {{ index+1 }}-{{ subIndex+1 }}、<span class="content-header_title">{{subItem.content}}</span>
                <span class="content-header_score">{{ subItem.score || 0 }}分</span>
                <div class="content-header_btngroup">
                  <el-button type="text" icon="el-icon-plus" @click="handleOpenUpload(subItem.id)">添加痕迹</el-button>
                  <el-button type="text" icon="el-icon-search" @click="handleOpenInfo(subItem.id)">查阅痕迹</el-button>
                </div>
              </div>
              <div class="content-time"><span v-show="subItem.create_time">截至时间：</span>
                {{ subItem.create_time | formatTime}}</div>
              <div class="content-desc"><span v-show="subItem.evaluation">考核标准: </span> {{ subItem.evaluation }}
              </div>
              <template>
                <div class="son-wrapper" style="margin-left:10px;">
                  <div class="content" v-for="(sonItem,sonIndex) in subItem.child" :key="sonIndex">
                    <div class="content-header">
                      {{ index+1 }}-{{ subIndex+1 }}-{{ sonIndex+1 }}、<span
                        class="content-header_title">{{sonItem.name}}</span>
                      <span class="content-header_score">{{ sonItem.score }}分</span>
                      <div class="content-header_btngroup">
                        <el-button type="text" icon="el-icon-plus" @click="handleOpenUpload(sonItem.id)">添加痕迹
                        </el-button>
                        <el-button type="text" icon="el-icon-search" @click="handleOpenInfo(sonItem.id)">查阅痕迹
                        </el-button>
                      </div>
                    </div>
                    <div class="content-time"><span v-show="sonItem.time">截至时间：</span> {{ sonItem.time}}</div>
                    <div class="content-desc"><span v-show="sonItem.evaluation">考核标准: </span> {{ sonItem.evaluation }}
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </template>
      </div>
    </div> -->
    <!-- 查看上传痕迹信息 -->
    <el-dialog title="查看痕迹" width="80%" :visible.sync="dialogFormVisible">
      <traces-list :targetId="markList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateIndex()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 打开文件上传窗口 -->
    <div class="fileup-wrapper">
      <el-dialog width="660px" :visible.sync="dialogUpperVisible">
        <el-row class="input-box">
          <span class="title">痕迹摘要</span>
          <el-input type="text" size="small" placeholder="请输入痕迹摘要" v-model="abstract"></el-input>
        </el-row>
        <file-upload ref="upload" :params="uploadParam" :targetId="targetId" postUrl="/api/Work/Mark/"></file-upload>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import {
    parseTime, getFileType
  } from "@/utils/index";
  import {
    getIndexByid,
    getMarkInfo
  } from "@/api/work.js";

  export default {
    name: "IndexShow",
    components: {
      'RelateTarget': () => import("@/views/markSys/taskCenter/components/relateTarget")
    },
    watch: {
      dialogUpperVisible(val) {
        if (!val) {
          this.abstract = ''
          this.$refs.upload.clear();
        }
      },
      abstract(val) {
        this.uploadParam.abstract = val
      }
    },
    data() {
      return {
        level: 1,
        dialogFormVisible: false,
        dialogUpperVisible: false,
        formatMarkData: [],
        targetId: null, // 指标ID
        uploadParam: {}, // 上传文件字段
        abstract: '', // 摘要
        initIndexId: null,
        markList: [], // 填报记录
        indexList: [],
        targetId: null,
        flattenIndexList: []
      };
    },
    created() {
      const id = this.$route.params && this.$route.params.id;
      this.targetId = id
      // this.fetchData(id);
    },
    methods: {
      fetchData(id) {
        getIndexByid(id).then(res => {
          this.flattenIndexList = this.flatten(res.data.tardetail)
          this.level = this.calcLevel(res.data.tardetail)
          this.$nextTick(() => {
            this.uniteTable('table', 2)
          })
        });
      },
      // 计算嵌套层级
      calcLevel(data) {
        let level = 1
          if (data.some(e => e.child && e.child.length)) {
            level = 2
            data.forEach(item => {
              if (item.child.some(e => e.child.length)) {
                level = 3
              }
            })
          }
        return level
      },
      // 合并表格
      uniteTable(tableId, colLength) { //表格ID，表格列数
        var tb = document.getElementById(tableId);
        tb.style.display = '';
        var i = 0;
        var j = 0;
        var rowCount = tb.rows.length; //   行数 
        var colCount = tb.rows[0].cells.length; //   列数 
        var obj1 = null;
        var obj2 = null;
        //为每个单元格命名 
        for (i = 0; i < rowCount; i++) {
          for (j = 0; j < colCount; j++) {
            tb.rows[i].cells[j].id = "tb__" + i.toString() + "_" + j.toString();
          }
        }
        // 合并行
        for (i = 0; i < colCount; i++) {
          if (i == colLength) break;
          obj1 = document.getElementById("tb__0_" + i.toString())
          for (j = 1; j < rowCount; j++) {
            obj2 = document.getElementById("tb__" + j.toString() + "_" + i.toString());
            if (obj1.innerText == obj2.innerText && ((obj2.innerText != "" || obj1.innerText != "") && (obj1
                .innerText != "-" ||
                obj2.innerText != "-")) && !obj2.getAttribute('colspan') && !obj1.getAttribute('colspan')) {
              obj1.rowSpan++;
              obj2.parentNode.removeChild(obj2);
            } else {
              obj1 = document.getElementById("tb__" + j.toString() + "_" + i.toString());
            }
          }
        }
      },
      // 扁平化指标信息
      flatten(group) {
        const result = []
        group.forEach((kid,index) => bfs(kid, [], index + 1))
        return result

        function bfs(node, path, index) {
          if (!node.child.length) {
            const [p, s, c] = path
            result.push({
              p,
              s,
              c: {
                content: node.content,
                evaluation: node.evaluation,
                score: node.score,
                id: node.id,
                index: index
              }
            })
          } else {
            path.push({
              content: node.content,
              evaluation: node.evaluation,
              score: node.score,
              id: node.id,
              index: index 
            })
            node.child.forEach((kid, i) => bfs(kid, path , index + '-'+ (i+1)))
            path.pop()
          }
        }

      },
      flattenMark(list) {
      const result = [];
      list.forEach(obj =>{
        
        let tempMark = null;
        if (!obj.markFile.length) {
          // tempMark = Object.assign(data, { file: "" ,fileType:''});
          let data = {
          abstract: obj.abstract,
          time: obj.create_time,
          user: obj.owner,
          file: '',
          fileType: '',
        };
          result.push(data);
        } else {
          obj.markFile.forEach(e => {
            let data = {
              abstract: obj.abstract,
              time: obj.create_time,
              user: obj.owner,
              file: e,
              fileType: getFileType(e,'.'),
            };
            result.push(data);
          });
        }
      })
      return result;
    },
      handleOpenInfo(id) {
        this.dialogFormVisible = true;
        this.initIndexId = id;
        this.fetchMarkInfo(id);
      },
      handleOpenUpload(id) {
        this.dialogUpperVisible = true;
        this.targetId = id;
        this.uploadParam = {
          targetdetail: this.targetId,
          // is_report: true,
          abstract: ''
        };
      },

      fetchMarkInfo(id) {
        getMarkInfo(id).then(res => {
          const data = res.data.results
          this.markList = this.flattenMark(data)
        });
      },

    }
  };

</script>
<style lang="scss">
  .index-container {
    padding: 20px;
    
  }

</style>
